package com.campus.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.app.mapper.CloudFileMapper;
import com.campus.app.service.CloudFilesService;
import com.campus.commons.entity.CloudFile;
import com.campus.commons.entity.WxIndexImage;
import com.campus.app.mapper.WxIndexImageMapper;
import com.campus.app.service.WxIndexImagesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.commons.utils.Error;
import com.campus.commons.utils.MyPage;
import com.campus.commons.utils.Result;
import com.campus.commons.utils.oss.AliOssCloudUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 轮播图表 服务实现类
 * </p>
 *
 * @author Rin
 * @since 2020-12-24
 */
@Service
public class WxIndexImageServiceImpl extends ServiceImpl<WxIndexImageMapper, WxIndexImage> implements WxIndexImagesService {

    @Autowired
    private CloudFilesService cloudFilesService;
    @Autowired
    private WxIndexImageMapper wxIndexImageMapper;

    @Override
    public Result<List<WxIndexImage>> getAllIndexImages(MyPage myPage) {
        return Result.result(wxIndexImageMapper.selectPage(
                new Page<WxIndexImage>(myPage.getPage(), myPage.getLimit()), null));
    }

    @Override
    public Result<List<WxIndexImage>> getIndexImages(MyPage<WxIndexImage> myPage) {
        LambdaQueryWrapper<WxIndexImage> queryWrapper = new QueryWrapper<WxIndexImage>().lambda();
        //根据类型，根据状态；
        WxIndexImage data = myPage.getData();
        queryWrapper.eq(data.getStart() != null ? true : false, WxIndexImage::getStart, data.getStart())
                .eq(data.getIndexTypeId() != null ? true : false, WxIndexImage::getIndexTypeId, data.getIndexTypeId());
        return Result.result(wxIndexImageMapper.selectPage(
                new Page<>(myPage.getPage(), myPage.getLimit()), queryWrapper));
    }

    @Override
    public Result addIndexImage(WxIndexImage wxIndexImage, MultipartFile file) {
        Integer startCount = getStartCount(wxIndexImage.getIndexTypeId(), wxIndexImage.getId());
        startCount += wxIndexImage.getStart() != null ? 1 : 0;
        if (startCount > 5) {
            return Result.error(Error.Operation_E1R, "这个页面的轮播已经达到上限了！");
        }
        String url = getUrlForInputStream(file);
        if (url.equals("")) {
             return Result.error(Error.File_E1R,"没有获取到轮播图片文件，操作中止");
        }
        wxIndexImage.setImage(url);
        return Result.result(wxIndexImageMapper.insert(wxIndexImage));
    }

    /**
     * 上传轮播图片获取url地址
     *
     * @param file
     * @return
     */
    private String getUrlForInputStream(MultipartFile file) {
        if (file != null) {
            try {
                Map<String, String> map = AliOssCloudUtil.uploadFIle(
                        file.getOriginalFilename(), file.getInputStream());
                String url = map.get("url");
                if (StringUtils.isBlank(url)) {
                    throw new RuntimeException("上传轮播图片发生异常，操作中止。");
                }
//                添加信息到数据库
                CloudFile cloudFile = new CloudFile("轮播资源",file.getOriginalFilename(),
                        file.getSize(),-1,map.get("fileRelativePath"));
                cloudFilesService.save(cloudFile);
                return url;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";

    }

    @Override
    public Result delIndexImage(Integer id) {
//         先差； 没有启动的才能删除？ ok
        WxIndexImage byId = getById(id);
        if (byId.getStart() == 1) {
            return Result.error(Error.Operation_E1R, "该轮播还在使用中，不能进行删除");
        }
        return Result.result(wxIndexImageMapper.deleteById(id));
    }

    @Override
    public Result upIndexImage(WxIndexImage wxIndexImage, MultipartFile file) {
        // 我要查询的；肯定是更新成的；限制前台必须穿类型过来；ok
        //错误情况  启动少于1 或者大于5;
        Integer startCount = getStartCount(wxIndexImage.getIndexTypeId(), wxIndexImage.getId());
        startCount += wxIndexImage.getStart() == 1 ? 1 : 0;
        if (startCount > 5) {
            return Result.error(Error.Operation_E1R, "这个页面的轮播已经达到上限了！");
        } else if (startCount < 1) {
            return Result.error(Error.Operation_E1R, "页面图片轮播最少一个.");
        }
        String url = getUrlForInputStream(file);
        if (!url.equals("")) {
        wxIndexImage.setImage(url);
        }
        return Result.result(wxIndexImageMapper.updateById(wxIndexImage));
    }

    /**
     * 返回已经启动的数量；
     *
     * @param indexType
     * @return
     */
    @Override
    public Integer getStartCount(Integer indexType, Integer id) {
        LambdaQueryWrapper<WxIndexImage> queryWrapper = new QueryWrapper<WxIndexImage>().lambda();
        //过滤id；
        queryWrapper.ne(id != null, WxIndexImage::getId, id);
        queryWrapper.eq(WxIndexImage::getIndexTypeId, indexType)
                .eq(WxIndexImage::getStart, 1);
        return wxIndexImageMapper.selectCount(queryWrapper);
    }
}
